package com.example.demo.utils;

import com.example.demo.domain.QrCodePosition;
import com.itextpdf.barcodes.BarcodePDF417;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Image;

public class QrCodeUtils {

    public static void addPdf417Code(PdfPage page, PageSize pageSize, String text) {
        System.out.println(text);
        QrCodePosition position = new QrCodePosition(0, 90, 50, 0);
        addPdf417Code(page, pageSize, position, text);
    }

    public static void addPdf417Code(PdfPage page, PageSize pageSize, QrCodePosition position, String text) {
        addPdf417Code(page, pageSize, position, text, 172f, 36f);
    }

    public static void addPdf417Code(PdfPage page, PageSize pageSize, QrCodePosition position, String text, Float width, Float height) {
        addPdf417Code(page, pageSize, position, text, width, height,null, null, null);
    }

    public static void addPdf417Code(PdfPage page, PageSize pageSize, QrCodePosition position, String text, Float width, Float height,
                                     Integer errorLevel, Integer columns, Integer rows) {
        // 创建对象
        BarcodePDF417 barcode = new BarcodePDF417();
        // 设置内容
        barcode.setCode(text);
        // 设置容错等级 0~8
        barcode.setErrorLevel(errorLevel == null ? 5 : errorLevel);
        // 设置列数
        barcode.setCodeColumns(columns == null ? 15 : columns);
        // 设置行数
        barcode.setCodeRows(rows == null ? 3 : rows);
        // 设置图片
        Image image = new Image(barcode.createFormXObject(page.getDocument()));
        // 设置二维码大小
        float imageWidth = width != null ? width : image.getImageWidth();
        float imageHeight = height != null ? height : image.getImageHeight();
        image.scaleAbsolute(imageWidth, imageHeight);
        // 设置二维码位置
        int x = position.isLeft() ? position.getLeft() : (int) (pageSize.getWidth() - imageWidth - position.getRight());
        int y = position.isBottom() ? position.getBottom() : (int) (pageSize.getHeight() - imageHeight - position.getBottom());
        image.setFixedPosition(x, y);
        // 添加二维码
        new Canvas(page, pageSize).add(image).close();
    }

}
